<template>
    <Upload
      v-model:file-list="fileList"
      v-bind="$attrs"
      name="avatar"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :customRequest="customRequest"
    >
      <a-button>上传</a-button>
    </Upload>
  </template>
  <script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { message,  Upload } from 'ant-design-vue';
  import type { UploadProps } from 'ant-design-vue';
  import { defHttp } from '@/utils/http/axios';
  const emit = defineEmits(['update:value', 'change'])
  const props = defineProps({
    value: {
        type: String,
        default: ''
    }
  })
  const fileList = ref([]);

  watch(() => props.value, (val) => {
    if (val) {
      if (typeof val === 'string') {
          fileList.value = [];
          val.split(',').forEach(url => {
              fileList.value.push({
                  uid: url,
                  name: '1',
                  status: 'done',
                  url
              })
          })
      } else {
        fileList.value = val;
      } 
    } else {
      fileList.value = [];
    }
  }, {immediate: true})
  const beforeUpload = (file: UploadProps['fileList'][number]) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const customRequest = async (params) => {
    const { file, onSuccess } = params;
    const res = await defHttp.post({ 
        url:'/admin/common/upload?fileType=image',
        headers: { 'content-type': 'multipart/form-data' },
        params: { file } 
    })
    fileList.value.forEach(f => {
      if (f.uid === file.uid) {
        f.url = res.absolute;
        f.status = 'done';
      }
    });
    const urlValue = fileList.value.map(f => f.url).join(',');
    debugger
    emit('update:value', urlValue);
    emit('change', urlValue);
    onSuccess(res, file);
  }
  </script>
  <style scoped>
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }
  
  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  </style>
  